package jmu.zzh.alumnus.user.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jmu.zzh.alumnus.common.util.CustomJWTUtils;
import jmu.zzh.alumnus.user.request.LoginRequest;
import jmu.zzh.alumnus.user.response.LoginResponse;
import jmu.zzh.alumnus.user.request.UserRequest;
import jmu.zzh.alumnus.user.request.UpdatePasswordRequest;
import jmu.zzh.alumnus.common.response.R;
import jmu.zzh.alumnus.user.service.UserService;
import jmu.zzh.alumnus.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    CustomJWTUtils customJWTUtils;

    @GetMapping("count")
    public R<Long> count() {
        return R.ok(userService.count());
    }

    @PostMapping({"login","admin-login"})
    public R<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest, HttpServletRequest request) {
        boolean isAdminLogin = request.getRequestURI().endsWith("admin-login");
        LoginResponse loginResponse = userService.login(loginRequest, isAdminLogin);
        return R.ok(loginResponse);
    }

    @PostMapping("register")
    public R<Integer> register(@Valid @RequestBody UserRequest userRequest){
        return R.ok(userService.register(userRequest));
    }

    @GetMapping("current")
    public R<User> getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7); // 去掉"Bearer "前缀
        String username = customJWTUtils.getUsernameFromToken(token);
        return R.ok(userService.getCurrentUser(username));
    }

    @PutMapping("info")
    public R<Integer> updateUserInfo(@RequestBody User user, HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7);
        String username = customJWTUtils.getUsernameFromToken(token);
        return R.ok(userService.updateUserInfo(username, user));
    }

    @PutMapping("password")
    public R<Integer> updatePassword(@Valid @RequestBody UpdatePasswordRequest passwordRequest, HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7);
        String username = customJWTUtils.getUsernameFromToken(token);
        return R.ok(userService.updatePassword(username, passwordRequest));
    }
}
